<?php

namespace App\Http\Services;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class Sms
{
    public static function send($phone, $type)
    {
        $code = str_pad(rand(1, 9999), 4, 0, STR_PAD_LEFT);

        try {
            $smsapi = "http://api.smsbao.com/"; //短信网关
            $user = "zybaoxian"; //短信平台帐号
            $pass = md5("zybaoxian123"); //短信平台密码
            $content="【中阳保险】您的验证码是{$code}。如非本人操作，请忽略本短信";//要发送的短信内容
            $sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".urlencode($phone)."&c=".urlencode($content);
            $result =file_get_contents($sendurl);
            if ($result != '0') {
                Log::error('短信发送失败---' . $result);
                return [
                    'code' => 0,
                    'msg' => '发送失败',
                ];
            }
        } catch (\Exception $e) {
            Log::error('短信发送失败', $e->getLine() . '=>' . $e->getMessage());
            return [
                'code' => 0,
                'msg' => '发送失败',
            ];
        }
        // }

        $key = 'smsCode_' . $type .'_'. $phone;
        $expiredAt = now()->addMinutes(10);
        // 缓存验证码 3分钟过期。
        Cache::put($key, $code, $expiredAt);
        return [
            'code' => 200,
            'msg' => '发送成功'
        ];
    }
}
